const User = require('../model/UserModel')
exports.list = async (req, res) => {
  const users = await User.find({}, { password: 0, version: 0 }).lean()
  res.json({
    message: '用户列表',
    code: 20000,
    data: {
      items: users,
      total: users.length
    }
  })
}

/**
 * 软删除
 */
exports.remove = (req, res) => {
  const id = req.params.id

  User.findByIdAndUpdate(
    id,
    { status: 1 },
    { new: true, select: 'status' },
    function (err, docs) {
      if (err) {
        throw new Error(err)
      }
      res.json({
        message: `软删除用户:${id}`,
        data: docs
      })
    }
  )
}

/**
 * 真正删除数据
 */
exports.realRemove = async (req, res) => {
  const id = req.params.id
  const result = await User.findByIdAndRemove(id, { rawResult: true })
  res.json({
    message: '真正删除',
    data: result,
    code: 20000
  })
}

exports.create = async (req, res) => {
  const data = req.body
  delete data._id
  const { name } = data
  const count = await User.countDocuments({ name })
  if (count > 0) {
    res.json({
      message: '用户创建失败,该用户已存在',
      code: 20001
    })
    return
  }
  data.password = '111111'
  const result = await User.create(data)
  res.json({
    message: '用户创建成功',
    data: result,
    code: 20000
  })
}

exports.updateUser = async (req, res) => {
  const id = req.params.id
  const data = req.body
  const result = await User.findByIdAndUpdate(id, data, { new: true })
  res.json({
    message: '用户更新成功',
    data: result,
    code: 20000
  })
}
